﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Windows.Devices.Geolocation;
using HappyTravelling.ThanhService;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace HappyTravelling.Views
{
    public partial class MeetingDetail : PhoneApplicationPage
    {
        public static DisplayListMeeting dlm;
        Geolocator geolocator = null;
        bool tracking = false;
        ProgressIndicator pi;
        MapLayer PushpinMapLayer;
        private GeoCoordinate CurrencyLocation;

        public MeetingDetail()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            tbDatingName.Text = dlm.TenCuocHen;
            tbTenAdmin.Text = dlm.TenAdmin;
            tbThoigian.Text = dlm.Time;
            
            pi = new ProgressIndicator();
            pi.IsIndeterminate = true;
            pi.IsVisible = false;
            
            PushpinMapLayer = new MapLayer();
            ChoosingMap.Layers.Add(PushpinMapLayer);
            var aPushpin = CreatePushpinObject2();
            MapOverlay MyOverlay = new MapOverlay();
            MyOverlay.Content = aPushpin;
            MyOverlay.GeoCoordinate = new GeoCoordinate(dlm.Location.Latitude, dlm.Location.Longitude);
            MyOverlay.PositionOrigin = new Point(0, 0.5);
            ChoosingMap.SetView(MyOverlay.GeoCoordinate,13);
            // Add the MapOverlay containing the pushpin to the MapLayer
            this.PushpinMapLayer.Add(MyOverlay);
            PushpinMapLayer.Add(new MapOverlay());
            GetListMember();
            base.OnNavigatedTo(e);
        }

        private void GetListMember()
        {
            WebService1SoapClient client = new WebService1SoapClient();
            client.GetMeetingUsersAsync(dlm.ID);
            client.GetMeetingUsersCompleted += ClientOnGetMeetingUsersCompleted;
        }

        private void ClientOnGetMeetingUsersCompleted(object sender, GetMeetingUsersCompletedEventArgs e)
        {
            string json = e.Result;
            var ListMeetingUser = JsonConvert.DeserializeObject<List<User>>(json);
            
            try
            {
                ListMember.ItemsSource = ListMeetingUser;
                foreach (var user in ListMeetingUser)
                {
                    var location = new GeoCoordinate();
                    location.Latitude = user.Latitude;
                    location.Longitude = user.Longtitude;
                    DrawPushpin(location,0);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void SetLocation(double latitude, double longitude, double zoomLevel, bool showLocator)
        {
            // Move the pushpin to geo coordinate
            var location = new GeoCoordinate();
            location.Latitude = latitude;
            location.Longitude = longitude;

            try
            {
                ChoosingMap.SetView(location, zoomLevel);
                //DrawPushpin(location,1);
                foreach (var layer in PushpinMapLayer)
                {
                    if (layer.GeoCoordinate == CurrencyLocation)
                    {
                        PushpinMapLayer.Remove(layer);
                    }
                }
                WebService1SoapClient client = new WebService1SoapClient();
                App.CurrentUser.Latitude = location.Latitude;
                App.CurrentUser.Longtitude = location.Longitude;
                client.UpdateLocationAsync(App.CurrentUser.id, location.Latitude, location.Longitude);

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            // Draw a pushpin
            

            // Show progress indicator while map resolves to new position
            pi.IsVisible = true;
            pi.IsIndeterminate = true;
            pi.Text = "Resolving...";
        }

        private void btResult_Click(object sender, RoutedEventArgs e)
        {
            if (!tracking)
            {
                geolocator = new Geolocator();
                geolocator.DesiredAccuracy = PositionAccuracy.High;
                geolocator.MovementThreshold = 50; // The units are meters.
                geolocator.PositionChanged += geolocator_PositionChanged;
                tracking = true;
                btResult.Content = "Đang định vị";
                this.ChoosingMap.ResolveCompleted += MapResolveCompleted;
            }
            else
            {
                geolocator.PositionChanged -= geolocator_PositionChanged;
                geolocator = null;
                tracking = false;
                btResult.Content = "Vị trí";
                this.ChoosingMap.ResolveCompleted -= MapResolveCompleted;
            }
        }
        void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            Dispatcher.BeginInvoke(() =>
            {
                GeoCoordinate positionCoord = new GeoCoordinate()
                {
                    Altitude = args.Position.Coordinate.Altitude.HasValue ? args.Position.Coordinate.Altitude.Value : 0.0,
                    Course = args.Position.Coordinate.Heading.HasValue ? args.Position.Coordinate.Heading.Value : 0.0,
                    HorizontalAccuracy = args.Position.Coordinate.Accuracy,
                    Latitude = args.Position.Coordinate.Latitude,
                    Longitude = args.Position.Coordinate.Longitude,
                    Speed = args.Position.Coordinate.Speed.HasValue ? args.Position.Coordinate.Speed.Value : 0.0,
                    VerticalAccuracy = args.Position.Coordinate.AltitudeAccuracy.HasValue ? args.Position.Coordinate.AltitudeAccuracy.Value : 0.0
                };

                // Center the map on the new location
                this.ChoosingMap.Center = positionCoord;

                this.ChoosingMap.ZoomLevel = 15;

                // Draw a pushpin
                //DrawPushpin(positionCoord,0);
                SetLocation(positionCoord.Latitude, positionCoord.Longitude, 13, tracking);
                // Show progress indicator while map resolves to new positi
                pi.IsVisible = true;
                pi.IsIndeterminate = true;
                pi.Text = "Resolving...";
                SystemTray.SetProgressIndicator(this, pi);
            });
        }

        private void MapResolveCompleted(object sender, MapResolveCompletedEventArgs e)
        {
            // Hide progress indicator
            pi.IsVisible = false;
            pi.IsIndeterminate = false;
            SystemTray.SetProgressIndicator(this, null);
        }

        private void DrawPushpin(GeoCoordinate coord, int k)
        {
            if (k == 0)
            {
                var aPushpin = CreatePushpinObject();
                MapOverlay MyOverlay = new MapOverlay();
                MyOverlay.Content = aPushpin;
                MyOverlay.GeoCoordinate = coord;
                MyOverlay.PositionOrigin = new Point(0, 0.5);

                // Add the MapOverlay containing the pushpin to the MapLayer
                this.PushpinMapLayer.Add(MyOverlay);
            } else if (k == 1)
            {
                var aPushpin = CreatePushpinObject2();
                MapOverlay MyOverlay = new MapOverlay();
                MyOverlay.Content = aPushpin;
                MyOverlay.GeoCoordinate = coord;
                MyOverlay.PositionOrigin = new Point(0, 0.5);

                // Add the MapOverlay containing the pushpin to the MapLayer
                this.PushpinMapLayer.Add(MyOverlay);
            }

            //Creating a MapOverlay and adding the Pushpin to it.
            
        }

        private Grid CreatePushpinObject()
        {
            //Creating a Grid element.
            Grid MyGrid = new Grid();
            MyGrid.RowDefinitions.Add(new RowDefinition());
            MyGrid.RowDefinitions.Add(new RowDefinition());
            MyGrid.Background = new SolidColorBrush(Colors.Transparent);

            //Creating a Rectangle
            Rectangle MyRectangle = new Rectangle();
            MyRectangle.Fill = new SolidColorBrush(Colors.Black);
            MyRectangle.Height = 20;
            MyRectangle.Width = 20;
            MyRectangle.SetValue(Grid.RowProperty, 0);
            MyRectangle.SetValue(Grid.ColumnProperty, 0);

            //Adding the Rectangle to the Grid
            MyGrid.Children.Add(MyRectangle);

            //Creating a Polygon
            Polygon MyPolygon = new Polygon();
            MyPolygon.Points.Add(new Point(2, 0));
            MyPolygon.Points.Add(new Point(22, 0));
            MyPolygon.Points.Add(new Point(2, 40));
            MyPolygon.Stroke = new SolidColorBrush(Colors.Black);
            MyPolygon.Fill = new SolidColorBrush(Colors.Black);
            MyPolygon.SetValue(Grid.RowProperty, 1);
            MyPolygon.SetValue(Grid.ColumnProperty, 0);

            //Adding the Polygon to the Grid
            MyGrid.Children.Add(MyPolygon);
            return MyGrid;
        }

        private Grid CreatePushpinObject2()
        {
            //Creating a Grid element.
            Grid MyGrid = new Grid();
            MyGrid.RowDefinitions.Add(new RowDefinition());
            MyGrid.RowDefinitions.Add(new RowDefinition());
            MyGrid.Background = new SolidColorBrush(Colors.Transparent);

            //Creating a Rectangle
            Rectangle MyRectangle = new Rectangle();
            MyRectangle.Fill = new SolidColorBrush(Colors.Red);
            MyRectangle.Height = 20;
            MyRectangle.Width = 20;
            MyRectangle.SetValue(Grid.RowProperty, 0);
            MyRectangle.SetValue(Grid.ColumnProperty, 0);

            //Adding the Rectangle to the Grid
            MyGrid.Children.Add(MyRectangle);

            //Creating a Polygon
            Polygon MyPolygon = new Polygon();
            MyPolygon.Points.Add(new Point(2, 0));
            MyPolygon.Points.Add(new Point(22, 0));
            MyPolygon.Points.Add(new Point(2, 40));
            MyPolygon.Stroke = new SolidColorBrush(Colors.Red);
            MyPolygon.Fill = new SolidColorBrush(Colors.Red);
            MyPolygon.SetValue(Grid.RowProperty, 1);
            MyPolygon.SetValue(Grid.ColumnProperty, 0);

            //Adding the Polygon to the Grid
            MyGrid.Children.Add(MyPolygon);
            return MyGrid;
        }

        private void btDirection_Click(object sender, RoutedEventArgs e)
        {

        }
    }

}